/*
 * Copyright 2007-2008 Michele Mostarda ( michele.mostarda@gmail.com ).
 * All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.asemantics.anthill;

import org.jivesoftware.smack.packet.Message;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Defines the base class for both {@link org.asemantics.anthill.CommandMessage}
 * and {@link org.asemantics.anthill.CommandResponseMessage}.
 */
public abstract class AbstractMessage extends Message {

    /**
     * The basic remote operation.
     */
    private final Class<? extends RemoteOperation> remoteOperation;

    /**
     * Constructor. <i>RemoteOperation</i> can be <code>null</code>
     * when an exception occurs during deserialization. 
     *
     * @param ro the remote operation who generated this message.
     */
    protected AbstractMessage(Class<? extends RemoteOperation> ro) {
        remoteOperation = ro;
    }

    /**
     * Returns the {@link org.asemantics.anthill.RemoteOperation} associated with this base message.
     * @return
     */
    protected Class<? extends RemoteOperation> getRemoteOperation() {
        return remoteOperation;
    }

    /**
     * Represents an empty command message parameters set.
     */
    public static final Map<String,Object> NO_PARAMETERS = new HashMap();

    /**
     * Returns all the properties into the message as couples property/propertyValue.
     * @param message
     * @return
     */
    protected static Map<String,Object> getMessageMap(Message message) {
        Iterator<String> propertyNames = message.getPropertyNames().iterator();
        String propertyName;
        Map<String,Object> result = new HashMap();
        while(propertyNames.hasNext()) {
            propertyName = propertyNames.next();
            result.put(propertyName, message.getProperty(propertyName));
        }
        return result;
    }
}
